package top.lingchen.blogadmin.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import top.lingchen.blogadmin.bean.Admin;

import java.util.ArrayList;

/**
 * @Author 凌宸
 * @create 2021-12-20 下午 2:34
 * @Description
 * @Version 1.0
 */
@Component
public class SecurityUserService implements UserDetailsService {

    @Autowired
    private AdminService adminService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 登录的时候，会把 username 传递到这里
        // 通过username 查询 admin表，如果 admin存在 将密码告诉 spring security
        // 如果不存在 返回 null，认证失败
        Admin admin = adminService.findAdminByUsername(username);
        if(admin == null){
            // 登录失败
            return null;
        }
        UserDetails userDetails = new User(username, admin.getPassword(), new ArrayList<>());
        return userDetails;
    }
}
